package com.suning.sawp.service.impl.assistant;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.intf.assistant.AssistantDaoService;
import com.suning.sawp.intf.assistant.AssistantService;
import com.suning.sawp.intf.assistant.Result;
import com.suning.sawp.po.assistant.Assistant;
import com.suning.sawp.service.util.BaseContants;
import com.suning.vgs.follow.remote.intf.ServiceNumRemoteService;
import com.suning.vgs.follow.remote.intf.StoreManRemoteService;

@Service
public class AssistantServiceImpl implements AssistantService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AssistantServiceImpl.class);

    private static final int LIMIT = 20;
    
    /**
     * 店+发送IM消息key
     */
    private static final String MSG_KEY = "ebuy_remote_msg";
    
    private static final String SEPARATOR = ",";
    
    @Autowired
    AssistantDaoService assistantDaoService;

    @Autowired
    StoreManRemoteService storeManRemoteService;
    
    @Resource
    ServiceNumRemoteService serviceNumRemoteService;
    
//    @Resource
//    HsRemoteService hsRemoteService;
    
    @Override
    public Assistant queryAssistant() {
        LOGGER.debug("queryAssistant IN");
        List<Assistant> assistants = this.queryAssistant(AssistantStatus.DUTY_ON.getAssistantStatus());
        if (CollectionUtils.isNotEmpty(assistants)) {
            return assistants.get(0);
        }
        LOGGER.debug("queryAssistant OUT");
        return null;
    }

    @Override
    public List<Assistant> queryAssistant(final String status) {
        LOGGER.debug("queryAssistant IN,status = " + status);
        Preconditions.checkArgument(StringUtils.isNotBlank(status), "queryAssistant : status is empty");
        List<Assistant> assistants = assistantDaoService.queryAllAssistat();
        LOGGER.debug("queryAssistant OUT");
        return ImmutableList.copyOf(Collections2.filter(assistants, new Predicate<Assistant>() {

            @Override
            public boolean apply(Assistant input) {
                return status.equals(input.getStatus());
            }

        }));
    }

    @Override
    public Result<Assistant> setupAssistant(String staffId) {
        LOGGER.debug("setupAssistant IN, staffId = " + staffId);
        Preconditions.checkNotNull(staffId);
        Result<Assistant> result = new Result<Assistant>();
        
        Assistant assistant= assistantDaoService.queryAssistatByStaffId(staffId);
        if(null != assistant && StringUtils.isNotBlank(assistant.getId())){
            if(AssistantStatus.DUTY_OFF.getAssistantStatus().equals(assistant.getStatus())){
                updateAssistantStatusToDUTYOFF();
                assistant.setStatus(AssistantStatus.DUTY_ON.getAssistantStatus());
                assistantDaoService.updateAssistat(assistant);
            }
            result.setData(assistant);
            return result;
        }
        
        String cloudGuideId = storeManRemoteService.queryCloudGuideIdByStaffId(staffId);
        
        /**
         * 为空，操作失败
         */

        if(StringUtils.isNotBlank(cloudGuideId)){
            updateAssistantStatusToDUTYOFF();
            Assistant assistantTemp2 = new Assistant();
            assistantTemp2.setCloudGuideId(cloudGuideId);
            assistantTemp2.setStaffId(staffId);
            assistantTemp2.setStatus(AssistantStatus.DUTY_ON.getAssistantStatus());
            assistantDaoService.addAssistat(assistantTemp2);
            result.setData(assistantTemp2);
        }else{
            LOGGER.warn("queryCloudGuideIdByStaffId,cloudGuideId is empty");
            result.setSuccessFlg(BaseContants.FAILED);
        }
        LOGGER.debug("setupAssistant OUT,result = " + result);
        return result;
    }

    private void updateAssistantStatusToDUTYOFF() {
        Assistant assistantTemp = queryAssistant();
        if (null != assistantTemp) {
            assistantTemp.setStatus(AssistantStatus.DUTY_OFF.getAssistantStatus());
            assistantDaoService.updateAssistat(assistantTemp);
        }
    }

    @Override
    public ReturnMsg<String> groupSendMsg(final String content, final String serviceNumId) {
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        returnMsg.setError("0000", "老IM关闭，功能暂时关闭");
        /*
         * 屏蔽IM功能暂时，后期接入云信之后在行放开
        try {
            SingleThreadFactory.getExecutorService().execute(new Runnable() {
                
                @Override
                public void run() {
                    //查询服务号队形的云导购Id
                    ServiceNumDto dto = serviceNumRemoteService.queryServiceNumByNumId(serviceNumId);
                    if (null != dto) {
                        String from = serviceNumRemoteService.queryCloudGuideIdByStaffId(dto.getServiceNumId());
                        if (StringUtils.isNotBlank(from)) {
                            String nickName = dto.getServiceNumName();
                            int startIndex = 0;
                            List<String> cgIds = storeManRemoteService.queryAllCloudGuideIds(startIndex, LIMIT);
                            while (cgIds.size() == LIMIT) {
                                // 批量发送消息
                                List<Map<String,Object>> messageList = new ArrayList<Map<String,Object>>();
                                Map<String,Object> msgMap = new HashMap<String,Object>();
                                msgMap.put("from", from);
                                StringBuilder sb = new StringBuilder();
                                for(String cgId : cgIds){
                                    if(StringUtils.isNotBlank(cgId)){
                                        sb.append(cgId).append(SEPARATOR);
                                    }
                                }
                                String to = sb.toString();
                                if(to.length() > 0){
                                    to = to.substring(0, to.length() - 1);
                                }
                                msgMap.put("to", to); 
                                msgMap.put("genre", "1");
                                msgMap.put("sender", nickName);
                                msgMap.put("content", content);
                                messageList.add(msgMap);
                                String data = GsonUtils.toJson(messageList, false);
                                LOGGER.debug("店+服务号发送消息请求:{}",data);
                                hsRemoteService.process(MSG_KEY, data);
                                
                                // 取下批次工号对应cloudGuideId
                                startIndex += LIMIT;
                                cgIds = storeManRemoteService.queryAllCloudGuideIds(startIndex, LIMIT);
                            }
                        }
                    }
                }
            });
        } catch (Exception e) {
            LOGGER.error("AssistantService.groupSendMsg ERROR", e);
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
        }*/
        
        return returnMsg;
    }

}
